package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Classname SpeedLimitAttrHandler
 * @Description 校验 限速速率 <= 带宽
 * @Author zhang.song
 * @Date 2021-02-23 11:10
 */
public class SpeedLimitAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {

    @Autowired
    IQuerySceneInstService querySceneInstService;
    public SpeedLimitAttrHandler() {
    }

    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        super.before(attr, inst, value, data);
        if(data.getTriggerStrategy() != null) {
            // 初始化加载页面时不校验，跳过初次加载时的属性 set 触发
            return;
        }
        if (KiteStringUtils.isEmpty(value)) {
            return;
        }
        String fieldName = attr.getFieldName();
        KiteAttr speedAttr = inst.getAttr("2_0000001");
        KiteAttr speedLimitAttr = inst.getAttr("2_0000005");
        if (Objects.nonNull(speedAttr) && Objects.nonNull(speedLimitAttr) && KiteStringUtils.isNotEmpty(getValue(speedAttr, fieldName, value)) && KiteStringUtils.isNotEmpty(getValue(speedLimitAttr, fieldName, value))) {
            float speedLimitFloatValue;
            if ("1_0000116".equals(getValue(speedLimitAttr, fieldName, value))) {
                // 手填速率
                KiteAttr speedEditAttr = inst.getAttr("2_0000098");
                String speedEditValue = getValue(speedEditAttr, fieldName, value);
                if (Objects.isNull(speedEditAttr) || KiteStringUtils.isEmpty(speedEditValue)) {
                    return;
                }

                Integer unit = (speedEditValue.endsWith("G")) ? 1024 : 1;
                speedEditValue = speedEditValue.replaceAll("[^0-9\\.]", "");
                if (KiteStringUtils.isEmpty(speedEditValue)) {
                    return;
                }
                speedLimitFloatValue = Float.valueOf(speedEditValue) * unit;
            } else {
                String speedLimitValue = Optional.ofNullable(getValueDesc(speedLimitAttr, fieldName, value)).orElse("0");
                speedLimitFloatValue = Float.valueOf(speedLimitValue.replaceAll("[^0-9\\.]", ""));
                if (speedLimitValue.endsWith("G")) {
                    speedLimitFloatValue = speedLimitFloatValue * 1024;
                }
            }
            String speedValue = Optional.ofNullable(getValueDesc(speedAttr, fieldName, value)).orElse("0");
            float speedFloatValue = Float.valueOf(speedValue.replaceAll("[^0-9\\.]", ""));
            if (speedValue.endsWith("G")) {
                speedFloatValue = speedFloatValue * 1024;
            }

            if (!KiteStringUtils.equalsAny("0.0", Float.toString(speedLimitFloatValue), Float.toString(speedFloatValue)) && speedLimitFloatValue > speedFloatValue) {
                BssException.throwOut("", "", "2_0000001".equals(fieldName)?"带宽需要大于等于选择的限速速率":"限速速率需要小于等于选择的带宽");
            }
        }

        String serviceOfferId = data.getServiceOfferId();
        String serviceOfferIdStr = querySceneInstService.getExtParameterValue(data.getSceneInstId(),"upServiceOfferId");
        if (KiteStringUtils.equalsAny("2826",serviceOfferId,serviceOfferIdStr)) {
            // 产品变更 校验升速、降速变更
            List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "BUSI_CHANGE_SERVICEOFFERID");
            String originValueName = getValueName(attr, attr.getOriginValue());
            String currentValueName = getValueName(attr, value);
            if(StringUtils.isBlank(originValueName) || StringUtils.isBlank(currentValueName) || Objects.isNull(serviceOfferIdList)){
                return;
            }
            //割接数据名称不是数字+单位时不校验
            String originStr = originValueName.replaceAll("[^0-9\\.]", "");
            String currentStr = currentValueName.replaceAll("[^0-9\\.]", "");
            if(KiteStringUtils.isAnyEmpty(originStr,currentStr)){
                return;
            }
            int originUnit = originValueName.endsWith("G") ? 1024 : 1;
            int currentUnit = currentValueName.endsWith("G") ? 1024 : 1;
            double current = Double.parseDouble(currentStr) * currentUnit;
            double origin = Double.parseDouble(originStr) * originUnit;
            if (serviceOfferIdList.contains("1020")){
                // 升速
                if(origin > current) {
                    BssException.throwOut("", "","升速带宽新值不能小于原始带宽值");
                }
            } else if (serviceOfferIdList.contains("1021")){
                // 降速
                if(origin < current) {
                    BssException.throwOut("", "","降速带宽新值不能大于原始带宽值");
                }
            }
        }
    }


    private static String getValueName (KiteAttr attr, String OriginValue){
        for(KiteAttrValue kiteAttrValue : attr.getAttrValues()) {
            if(kiteAttrValue.getAttrValue().equalsIgnoreCase(OriginValue)) {
                return kiteAttrValue.getAttrValueName();
            }
        }
        return null;
    }

    /**
     * 取属性value值，如果属性=当前触发事件的属性，attr里的还是旧值，此时直接取入参里的value
     * @author zhang.song
     * @date 2021-02-23 15:24
     * @param attr
     * @param fieldName
     * @param value
     * @return java.lang.String
     */
    private static String getValue(KiteAttr attr, String fieldName, String value) {
        if (Objects.isNull(attr)) {
            return null;
        }

        if(fieldName.equals(attr.getFieldName())) {
            return value;
        } else {
            return attr.getValue();
        }
    }

    /**
     * 取属性显示值valueDesc，如果属性=当前触发事件的属性，attr里的还是旧值，此时用入参里的value查询显示值
     * @author zhang.song
     * @date 2021-02-23 15:24
     * @param attr
     * @param fieldName
     * @param value
     * @return java.lang.String
     */
    private static String getValueDesc(KiteAttr attr, String fieldName, String value) {
        if (Objects.isNull(attr)) {
            return null;
        }

        if(fieldName.equals(attr.getFieldName())) {
            List<KiteAttrValue> list = attr.getAttrValues();
            for (KiteAttrValue kiteAttrValue: list) {
                if(value.equals(kiteAttrValue.getAttrValue())) {
                    return kiteAttrValue.getAttrValueName();
                }
            }
            return null;
        } else {
            return attr.getValueDesc();
        }
    }
}
